#import "NetworkManager.h"

@implementation NetworkManager

/// 单例实现
+ (instancetype)sharedManager {
    static NetworkManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[NetworkManager alloc] init];
        [instance setupDefaultConfig];
    });
    return instance;
}

-(NSString *)baseURL{
    NSString *url=@"12346787643";
    
    return [url copy];
}

/// 初始化默认配置
- (void)setupDefaultConfig {
    // 默认超时时间30秒
    self.timeoutInterval = 30.0f;
    
    // 配置默认请求头
    [self configHTTPHeaderFields:@{@"Content-Type": @"application/json"}];
    
    // 配置AFHTTPSessionManager
    self.sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
    self.sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
    self.sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
}

/// AFHTTPSessionManager实例
- (AFHTTPSessionManager *)sessionManager {
    static AFHTTPSessionManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [AFHTTPSessionManager manager];
    });
    manager.requestSerializer.timeoutInterval = self.timeoutInterval;
    return manager;
}

/// 配置请求头
- (void)configHTTPHeaderFields:(NSDictionary<NSString *,NSString *> *)headerFields {
    if (headerFields && headerFields.count > 0) {
        for (NSString *key in headerFields.allKeys) {
            NSString *value = headerFields[key];
            [self.sessionManager.requestSerializer setValue:value forHTTPHeaderField:key];
        }
    }
}

/// 拼接完整URL
- (NSString *)completeURLWithString:(NSString *)urlString {
    if (self.baseURL && urlString && ![urlString hasPrefix:@"http"]) {
        return [self.baseURL stringByAppendingString:urlString];
    }
    return urlString;
}

/// 通用网络请求方法
- (NSURLSessionDataTask *)requestWithMethod:(RequestMethod)method
                                 urlString:(NSString *)urlString
                                 parameters:(id)parameters
                                   progress:(ProgressBlock)progress
                                    success:(SuccessBlock)success
                                    failure:(FailureBlock)failure {
    // 检查网络连接
    if (![self isNetworkReachable]) {
        NSError *error = [self errorWithCode:-1009 message:@"网络连接不可用，请检查网络设置"];
        if (failure) {
            failure(error);
        }
        return nil;
    }
    
    // 拼接完整URL
    NSString *completeURL = [self completeURLWithString:urlString];
    if (!completeURL) {
        NSError *error = [self errorWithCode:-1000 message:@"URL地址无效"];
        if (failure) {
            failure(error);
        }
        return nil;
    }
    
    AFHTTPSessionManager *manager = self.sessionManager;
    NSURLSessionDataTask *task = nil;
    
    // 根据请求方法选择不同的请求方式
    switch (method) {
        case RequestMethodGET:{
            task = [manager GET:completeURL parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                if (progress) {
                    progress(downloadProgress);
                }
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self handleSuccessResponse:responseObject success:success];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self handleFailureResponse:error failure:failure];
            }];
        }
            break;
            
        case RequestMethodPOST:{
            task = [manager POST:completeURL parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
                if (progress) {
                    progress(uploadProgress);
                }
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self handleSuccessResponse:responseObject success:success];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self handleFailureResponse:error failure:failure];
            }];
        }
          
            break;
            
        case RequestMethodPUT:{
            task = [manager PUT:completeURL parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self handleSuccessResponse:responseObject success:success];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self handleFailureResponse:error failure:failure];
            }];
        }
            
            break;
            
        case RequestMethodDELETE:{
            task = [manager DELETE:completeURL parameters:parameters headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self handleSuccessResponse:responseObject success:success];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                [self handleFailureResponse:error failure:failure];
            }];
        }
            break;
    }
    
    return task;
}

/// GET请求
- (NSURLSessionDataTask *)getWithUrlString:(NSString *)urlString
                                parameters:(id)parameters
                                   success:(SuccessBlock)success
                                   failure:(FailureBlock)failure {
    return [self requestWithMethod:RequestMethodGET
                         urlString:urlString
                         parameters:parameters
                           progress:nil
                            success:success
                            failure:failure];
}

/// POST请求
- (NSURLSessionDataTask *)postWithUrlString:(NSString *)urlString
                                 parameters:(id)parameters
                                    success:(SuccessBlock)success
                                    failure:(FailureBlock)failure {
    return [self requestWithMethod:RequestMethodPOST
                         urlString:urlString
                         parameters:parameters
                           progress:nil
                            success:success
                            failure:failure];
}

/// 上传文件
- (NSURLSessionDataTask *)uploadWithUrlString:(NSString *)urlString
                                   parameters:(id)parameters
                                     fileData:(NSData *)fileData
                                     fileName:(NSString *)fileName
                                     mimeType:(NSString *)mimeType
                                     progress:(ProgressBlock)progress
                                      success:(SuccessBlock)success
                                      failure:(FailureBlock)failure {
    if (!fileData) {
        NSError *error = [self errorWithCode:-2000 message:@"文件数据为空"];
        if (failure) {
            failure(error);
        }
        return nil;
    }
    
    // 检查网络连接
    if (![self isNetworkReachable]) {
        NSError *error = [self errorWithCode:-1009 message:@"网络连接不可用，请检查网络设置"];
        if (failure) {
            failure(error);
        }
        return nil;
    }
    
    // 拼接完整URL
    NSString *completeURL = [self completeURLWithString:urlString];
    if (!completeURL) {
        NSError *error = [self errorWithCode:-1000 message:@"URL地址无效"];
        if (failure) {
            failure(error);
        }
        return nil;
    }
    
    AFHTTPSessionManager *manager = self.sessionManager;
    
    NSURLSessionDataTask *task = [manager POST:completeURL parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        // 上传文件数据
        [formData appendPartWithFileData:fileData
                                    name:@"file"
                                fileName:fileName
                                mimeType:mimeType];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress) {
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self handleSuccessResponse:responseObject success:success];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self handleFailureResponse:error failure:failure];
    }];
    
    return task;
}

/// 处理成功响应
- (void)handleSuccessResponse:(id)responseObject success:(SuccessBlock)success {
    // 可以在这里统一处理返回数据，比如判断业务逻辑错误等
    if (success) {
        success(responseObject);
    }
}

/// 处理失败响应
- (void)handleFailureResponse:(NSError *)error failure:(FailureBlock)failure {
    // 统一处理错误信息
    NSError *handleError = [self handleError:error];
    if (failure) {
        failure(handleError);
    }
}

/// 统一错误处理
- (NSError *)handleError:(NSError *)error {
    NSString *errorMessage = @"请求失败，请稍后重试";
    
    if (error.code == NSURLErrorTimedOut) {
        errorMessage = @"请求超时，请稍后重试";
    } else if (error.code == NSURLErrorCannotConnectToHost) {
        errorMessage = @"无法连接到服务器";
    } else if (error.code == NSURLErrorNetworkConnectionLost) {
        errorMessage = @"网络连接已断开";
    } else if (error.code == NSURLErrorNotConnectedToInternet) {
        errorMessage = @"网络未连接，请检查网络设置";
    }
    
    // 可以根据实际业务需求添加更多错误处理
    
    return [self errorWithCode:error.code message:errorMessage];
}

/// 创建自定义错误
- (NSError *)errorWithCode:(NSInteger)code message:(NSString *)message {
    return [NSError errorWithDomain:@"NetworkErrorDomain"
                               code:code
                           userInfo:@{NSLocalizedDescriptionKey: message ?: @"未知错误"}];
}

/// 检查网络连接
- (BOOL)isNetworkReachable {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    return manager.isReachable;
}

/// 取消所有请求
- (void)cancelAllRequests {
    [[self.sessionManager operationQueue] cancelAllOperations];
}

/// 根据URL取消请求
- (void)cancelRequestWithURLString:(NSString *)urlString {
    if (!urlString) return;
    
    NSString *completeURL = [self completeURLWithString:urlString];
    NSURL *url = [NSURL URLWithString:completeURL];
    
    for (NSURLSessionTask *task in self.sessionManager.tasks) {
        if ([task.originalRequest.URL isEqual:url]) {
            [task cancel];
        }
    }
}

@end
